<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">{{ form_name }}</div>
        <div class="flex">
          <el-button
            type="primary"
            @click="
              init_form_data(
                right_list.filter((i) => {
                  return i.right_code == 'add'
                })[0]
              )
            "
            v-if="
              right_list.some((i) => {
                return i.right_code == 'add'
              })
            "
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          label="序号"
          type="index"
          width="100px"
        ></el-table-column>
        <el-table-column
          v-for="i in header_list"
          :prop="i.prop"
          :sortable="i.showTable ? true : false"
          :label="i.showTable ? i.label : ''"
          :width="i.showTable ? '' : 0 + 'px'"
          :key="i.label"
        >
        </el-table-column>
        <el-table-column label="操作" v-if="!loading">
          <template #default="scope: any">
            <div class="flex_cc" style="gap: 10px">
              <div
                v-for="item in right_list.filter((i) => {
                  return i.right_code != 'add' && i.right_code != 'query'
                })"
              >
                <el-button
                  v-if="right_fun(item, scope.row)"
                  @click="init_form_data(item, scope.row)"
                  >{{ item.right_name }}</el-button
                >
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:current-page="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <template #title>
        <h4>{{ right_name }}</h4>
      </template>
      <template #default>
        <currForm
          :formData="form_data"
          :formItmeList="curr_form_item_list"
          :formId="formId"
          :rowId="rowId"
          :axiosType="axiosType"
          :right_method="right_method"
          @close="show_box = false"
        ></currForm>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {
  check_role,
  debounce,
  dictData,
  handle_search_key,
} from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed, nextTick } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import currForm from './components/form.vue'
import { getBaseURL } from '@/service/BaseURL'

const baseURL = getBaseURL()
const router = useRouter()
const header_list = ref([])
const height_size = ref(1)
const list = ref([])
const total = ref<number>(0)
const loading = ref(false)
const max_height = ref()
const page_data = ref({
  current: 1,
  pageSize: 10,
  basicId: computed(() => {
    return formId.value
  }),
  valueMap: {},
})

const show_box = ref(false)
const form_name = ref('')
const right_name = ref('') // 按钮名
const right_method = ref('') // 按钮对接接口方式
const formId = ref('')
const rowId = ref('') // 行ID
const axiosType = ref('')
const curr_form_item_list = ref([])
const right_list = ref([]) // 权限参数
const form_data = ref() // 表单
const form_list = ref([])
const form_index = ref(0)
const condition_list = ref([])
const init_form_data = (...e) => {
  console.log(e)
  rowId.value = ''
  curr_form_item_list.value = e[0].operate_right_data
  right_name.value = e[0].right_name
  right_method.value = e[0].right_method
  axiosType.value = e[0].right_code
  if (e[1]) {
    rowId.value = e[1].id
  }
  // 表单提交型
  if (e[0].right_type == 1) {
    let obj = {}
    e[0].operate_right_data.forEach((i) => {
      if (e[1]) {
        // 新增之外的 TODO
        obj[i.code] = e[1][i.code]
      } else {
        // 新增
        obj[i.code] = Array.isArray(i.value) ? [] : ''
      }
    })
    form_data.value = obj
    console.log(form_data.value)
    nextTick(() => {
      show_box.value = true
    })
  } else {
    // 弹窗确认型
    ElMessageBox.confirm('确定' + e[0].right_name + '该记录吗？', '', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.formData_curd + '/' + e[1].id,
            method: e[0].right_method,
          })
          .then((res) => {
            console.log(res)
            ElMessage.success('操作成功！')
            get_data_list()
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}

onMounted(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  get_list()
  EventBus.on('submit_succ', () => {
    get_data_list()
    show_box.value = false
  })
  EventBus.on('refresh', () => {
    get_list()
  })
})
onUnmounted(() => {
  EventBus.off('submit_succ')
})
const get_list = () => {
  axios
    .request({
      url: serviceApi.form_list,
      method: 'post',
      data: {
        code: router.currentRoute.value.path,
        name: '',
        status: '',
        menuLocation: '',
        type: '',
        mould: '',
      },
    })
    .then((res) => {
      console.log(res)
      if (res.data.length) {
        form_name.value = res.data[0].name
        formId.value = res.data[0].id
        get_info(res.data[0].id)
      } else {
        ElMessage.warning('该列表暂无表单配置！')
      }
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const get_info = (e) => {
  axios
    .request({
      url: serviceApi.form_configForm_info,
      method: 'get',
      params: { id: e },
    })
    .then((res) => {
      console.log(JSON.parse(res.data.rightJson))
      right_list.value = JSON.parse(res.data.rightJson)
      form_list.value = JSON.parse(res.data.formJson)
      condition_list.value = JSON.parse(res.data.conditionJson)
      header_list.value = []
      JSON.parse(res.data.controlJson).forEach((i) => {
        if (i.show_table) {
          let obj = {
            value: '',
            label: i.name,
            showTable: true,
            type:
              i.item_type == 'input_number' || i.item_type == 'upload'
                ? 'input'
                : i.item_type == 'radio'
                ? 'select'
                : i.item_type == 'time'
                ? 'date'
                : i.item_type,
            isShow: true,
            options: i.data,
            prop: i.code,
            key: i.name,
          }
          header_list.value.push(obj)
        }
      })
      console.log(header_list.value)
      get_data_list()
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const get_data_list = () => {
  let axios_obj = right_list.value.filter((i) => {
    return i.right_code == 'query'
  })
  if (loading.value) return
  loading.value = true
  axios
    .request({
      url: serviceApi.formData_list,
      method: axios_obj[0].right_method,
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}

let list_debounce = debounce(200, get_data_list)
const right_fun = (...e) => {
  console.log(e)
  let hasRight = false
  if (e[0].pre_right_data.length) {
    let str = ''
    let keys = Object.keys(e[1])
    let values = Object.values(e[1])
    e[0].pre_right_data.forEach((i, index) => {
      str +=
        i.code +
        '=' +
        i.value.toString() +
        (index != e.length - 1 ? i.relate : '')
      let arr = str.split('||')
      hasRight = arr.some((i) => {
        return i.includes('&&')
          ? i.split('&&').every((ii) => {
              return (
                keys.includes(ii.split('=')[0]) &&
                values.includes(ii.split('=')[1])
              )
            })
          : keys.includes(i.split('=')[0]) && values.includes(i.split('=')[1])
      })
    })
  } else {
    hasRight = true
  }
  return hasRight
}
const search_key = () => {}
const condition_fun = (e) => {
  let children_list = []
  form_list.value[form_index.value].layout_list.forEach((item) => {
    children_list = children_list.concat(item.children_list)
  })
  let code_arr = []
  children_list.forEach((i) => {
    code_arr.push(i.code)
  })
  let value_arr = []
  children_list.forEach((i) => {
    value_arr.push(i.value + '')
  })
  let str = ''
  e.forEach((i, index) => {
    str +=
      i.code +
      '=' +
      i.value.toString() +
      (index != e.length - 1 ? i.relate : '')
  })
  let arr = str.split('||')
  return arr.some((i) => {
    return i.includes('&&')
      ? i.split('&&').every((ii) => {
          return (
            code_arr.includes(ii.split('=')[0]) &&
            value_arr.includes(ii.split('=')[1])
          )
        })
      : code_arr.includes(i.split('=')[0]) &&
          value_arr.includes(i.split('=')[1])
  })
}
// 显示条件校验 当前表单控件的值满足所有该控件的条件
const validata_condition = (e) => {
  if (!condition_list.value.length) return true
  let arr = condition_list.value[0].condition_list.filter((item) => {
    return item.type == 'display'
  })
  return condition_fun(arr[0].children_list)
}
</script>

<style lang="scss" scoped></style>
